package com.qf.user.manager.service.impl;

import com.qf.common.model.QfUser;
import com.qf.user.manager.bean.LoginUser;
import com.qf.user.manager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * SpringSecurity框架的UserDetailService接口实现类
 * @author 千锋健哥
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //1. 根据用户名, 到数据库获取用户对象
        QfUser user = userService.getUserByUserName(username);

        //2. 如果用户对象为空, 那么抛出用户名不存在异常
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在!");
        }

        //3. 根据用户名到数据库中查询对应的菜单集合
        List<String> menuList = userService.findUserMenuByUserName(username);

        //4. 将菜单集合转换为SpringSecurity的权限集合对象
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String menu : menuList) {
            authorities.add(new SimpleGrantedAuthority(menu));
        }

        //5. 封装SpringSecurity的UserDetails用户对象返回
        LoginUser loginUser = new LoginUser();
        //从数据库中查询到的用户对象
        loginUser.setQfUser(user);
        //根据用户名从数据库查到的这个用户的菜单集合对象
        loginUser.setAuthorities(authorities);
        return loginUser;
    }

}
